import {Button,  Spin} from 'antd'
import isEmpty from 'lodash/isEmpty'
import forEach from 'lodash/forEach'
import {WeaSearchGroup,WeaRightMenu,WeaDialog,WeaNewScroll, WeaFormItem, WeaAlertPage} from 'ecCom'
import {WeaSwitch} from 'comsMobx';
import { inject, observer} from 'mobx-react';
import * as mobx from 'mobx';
import '../../style/roleset.less';
import {WeaTableNew} from 'comsMobx';
import {i18n} from '../../public/i18n';
const WeaTable = WeaTableNew.WeaTable;
const toJS = mobx.toJS;

@inject('hrmRoleSet')
@inject('hrmCard')
@observer
class HrmRoleSet extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount(){
    const {hrmCard} = this.props;
    hrmCard.setTopButtons(this.getTopButtons.bind(this));
    hrmCard.setTopRightMenus(this.getRightMenu.bind(this));
    hrmCard.setTopShowDropIcon(true);
    this.init();
  }

  init() {
    const {hrmRoleSet} = this.props;
    let hrmId = this.props.params.hrmId || '';
    hrmRoleSet.init();
    hrmRoleSet.getData({id:hrmId});
  }

  getHrmRoleSetForm() {
    const { hrmRoleSet } = this.props;
    const { form,formFields } = hrmRoleSet;
    const {isFormInit} = form;
    let group = [];

    const formParams = form.getFormParams();
    isFormInit && !isEmpty(formFields) && toJS(formFields).map((c, i) =>{
      c.items.map((fields, j) => {
        let dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@f2m9ad@${j}`} fieldConfig={fields} form={form} formParams={formParams}/>;
        group.push(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@tzsfpv@${j}`}
          label={`${fields.label}`}
          labelCol={{span: `${fields.labelcol}`}}
          wrapperCol={{span: `${fields.fieldcol}`}}>
            {dom}
          </WeaFormItem>);
      });
    });
    return group;
  }

  reRenderColumns(columns){
    let _this = this;
    columns.forEach(c=>{
      if (c.dataIndex=='roleid'){
        c.render = function(text, record){
            return  <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={()=>_this.edit(record.id)} dangerouslySetInnerHTML={{__html: record.roleidspan}}></span>
        }
      }else {
          c.render = function(text, record){
              let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
              return <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
            }
        }
    })
    return columns;
  }

  onOperatesClick=(record,index,operate,flag,argumentString)=>{
    const func = operate.href ? operate.href.split(':')[1].split('(')[0] : '';
    let id = record.id ? record.id : '';
    if(func=='showLog'){
      id = record.roleid ? record.roleid : '';
    }
    this[func] && this[func](id);
  }

  doSave() {
    let hrmId = this.props.params.hrmId || '';
    const {hrmRoleSet} = this.props;
    hrmRoleSet.save(hrmId);
  }

  onCancel(){
    const {hrmRoleSet} = this.props;
    hrmRoleSet.onCancel();
  }

  update(){
    const {hrmRoleSet} = this.props;
    hrmRoleSet.update();
  }

  edit(id){
    const {hrmRoleSet} = this.props;
    let hrmId = this.props.params.hrmId || '';
    hrmRoleSet.edit(id, hrmId);
  }

  add(){
    const {hrmRoleSet} = this.props;
    let hrmId = this.props.params.hrmId || '';
    hrmRoleSet.add({id: hrmId});
  }

  delBatch(){
    const {hrmRoleSet} = this.props;
    const keys = this.getSelectedRowKeys();
    const ids = keys ? keys.join(',') : '';

    hrmRoleSet.delBatch(ids);
  }

  del(id){
    const {hrmRoleSet} = this.props;
    hrmRoleSet.delBatch(id);
  }

  showLog(id){
    let params = {targetId:id};
    params.logType = '4';
    params.logSmallType = '1012';
    window.setLogViewProps(params);
  }

  getSelectedRowKeys(){
    const { hrmRoleSet } = this.props;
    const { table } = hrmRoleSet;
    const selectedRowKeys = table.selectedRowKeys;
    return selectedRowKeys;
  }

  definedColumn() {
    const { hrmRoleSet } = this.props;
    const { table} = hrmRoleSet;
    table.setColSetVisible(true);
    table.tableColSet(true);
  }

  getRightMenu(){
    const keys = this.getSelectedRowKeys();
    const {hrmRoleSet} = this.props;
    const {hasRight, buttons} = hrmRoleSet;


    const opMenus = [];
    if (hasRight) {
      opMenus.push({
        icon: <i className='icon-coms-New-Flow'/>,
        content:i18n.button.add(),
        key: 'add',
        onClick: key =>{
          this.add();
        }
      });
      opMenus.push({
        icon: <i className='icon-coms-Batch-delete'/>,
        content:i18n.button.multiDelete(),
        key: 'delBatch',
        onClick: key =>{
          this.delBatch();
        }
      });
    } 

    const arr = [...opMenus, {
        icon: <i className='icon-coms-task-list'/>,
        content:i18n.button.columnVisibleSetting(),
        key: 'definedColumn',
        onClick: key =>{
          this.definedColumn();
        }
      }
    ];
    arr.push(
      {
        icon: <i className='icon-coms-Print-log'/>,
        content:i18n.button.log(),
        key: 'showLog',
        onClick: key =>{
          this.showLog();
        }
      }
    )
    return arr;
  }

  getTopButtons() {
    const {hrmRoleSet} = this.props;
    const {hasRight, buttons} = hrmRoleSet;

    const btnAdd = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ljjd98`} type="primary" onClick={()=>{this.add()}}>{i18n.button.add()}</Button>;
    const btns = [];
    if (hasRight) {
        btns.push(btnAdd);
    } 
    return btns;
  }
  
  render() {
    const {hrmRoleSet} = this.props;
    const {dialogShow, isEditor, hasRight, verified,formFields,table,} = hrmRoleSet;
    let customComponent = <div className="customComponent">
                            <i style={{margin: '0 10px'}}
                              className="icon-coms-Add-to-hot detailBtn"
                              title={i18n.button.add()}
                              onClick={() => this.add()}/>
                            <i
                              className="icon-coms-form-delete-hot detailBtn"
                              title={i18n.button.delete()}
                              onClick={()=>this.delBatch()} />
                        </div>;
    if (verified && !hasRight) {
      return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@jqqm22`} >
              <div style={{color : '#000'}}>
                  {i18n.message.authFailed()}
              </div>
          </WeaAlertPage>
      )
    }

    if (verified && hasRight) {
      return (
        <div className='wea-myhrm-roleset' style={{background: '#ffffff',height:'100%', position: 'relative'}}>
            <div style={{height: '100%'}}>
                <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@t5dovn`} needTigger={true} title={i18n.label.role()} showGroup={true} customComponent={customComponent}>
                  <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@oxpksq`}
                  comsWeaTableStore={table}
                  hasOrder={true}
                  needScroll={true}
                  //getColumns={c=>this.reRenderColumns(c)}
                  onOperatesClick={this.onOperatesClick}
                  />
                </WeaSearchGroup>
              <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@xrycwm`}
                title={isEditor?i18n.label.editRole():i18n.label.addRole()}
                icon="icon-coms-hrm"
                iconBgcolor="#217346"
                visible={dialogShow}
                onCancel={() => this.onCancel()}
                buttons={<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vrrst5`} type="primary"  onClick={() => this.doSave()}>{i18n.button.save()}</Button>}
                style={{width: 500, height: 160}}
              > 
              <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@6aammo`} height={180} ref="scrollBar">
              <div style={{paddingLeft:50,paddingTop:30}}>
              {this.getHrmRoleSetForm()}
              </div>
              </WeaNewScroll>
            </WeaDialog>
            </div>
        </div>
      )
    }

    return (
      <div></div>
    )
  }
}

export default HrmRoleSet;